<template>
   <el-drawer :title="modalName" v-model="addVisible" @close="modalClose" size="60%">
    <!-- 添加删除行 -->
    <div class="modify-row">
      <div class="insert-row">
        <el-input v-model.number="insertRowNumber" placeholder="请输入数字">
          <template v-slot:append>
            <el-icon class="minus-icon" @click="decrease(1)"><Minus /></el-icon>
            <el-icon class="plus-icon" @click="increase(1)"><Plus /></el-icon>
          </template>
        </el-input>
        <el-button class="modify-row-btn" type="primary" @click="addTableData">添加</el-button>
      </div>
      <div class="delete-row">
        <el-input v-model.number="deleteRowNumber" placeholder="请输入数字">
          <template v-slot:append>
            <el-icon class="minus-icon" @click="decrease(2)"><Minus /></el-icon>
            <el-icon class="plus-icon" @click="increase(2)"><Plus /></el-icon>
          </template>
        </el-input>
        <el-button class="modify-row-btn" type="primary" @click="deleteTableData">删除</el-button>
      </div>
    </div>
    
    <el-table @cell-click="handleFathCellDBClick" :data="fathTableData">
      <el-table-column type="expand">
        <template #default="props">
          <el-table @cell-click="handleCellDBClick" :data="tableData">
            <!-- 生成列-->
            <el-table-column v-for="column in tableHeader" :prop="column.prop">
              <template #header>
                  <el-tooltip class="item" effect="dark" :content="'这是必填项'" placement="top">
                    <div class="cell-flex">
                      <span v-if="column.prop !== 'seq'" style="color: red;margin-right: 5px;">*</span>
                      <span>{{ column.label }}</span>
                    </div>
                  </el-tooltip>
              </template>
              <template #default="scope">
                <!-- 双击时展示input-->
                <div class="cell-flex">
                  <!-- <span style="color: red;margin-right: 5px;" v-if="column.prop !== 'seq' && isEdit === column.prop && rowIndex === (scope.$index + 1)">*</span> -->
                  <!-- <span style="color: red;margin-right: 5px;" v-else-if="column.prop === 'isUsed'">*</span> -->
                  <el-input :id="column.prop" v-if="column.prop !== 'seq' && column.prop !== 'isUsed' && isEdit === column.prop && rowIndex === (scope.$index + 1)"
                    v-model="scope.row[column.prop]" @blur="isEdit=''">
                  </el-input>
                  <el-select v-model="scope.row[column.prop]" v-else-if="column.prop === 'isUsed'" @blur="isEdit=''">
                    <el-option
                      v-for="item in dict.isUsed"
                      :key="item.dictId"
                      :label="item.dictName"
                      :value="item.dictId"/>
                  </el-select>
                  <span v-else >{{scope.row[column.prop]}}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <!-- 生成列-->
      <el-table-column v-for="column in fathTableHeader" :prop="column.prop">
        <template #header>
          <el-tooltip class="item" effect="dark" :content="'这是必填项'" placement="top">
            <div class="cell-flex">
              <span v-if="column.prop !== 'seq'" style="color: red;margin-right: 5px;">*</span>
              <span>{{ column.label }}</span>
            </div>
          </el-tooltip>
        </template>
        <template #default="scope">
          <!-- 双击时展示input-->
          <div class="cell-flex">
            <!-- <span style="color: red;margin-right: 5px;" v-if="isFathEdit === column.prop">*</span> -->
            <el-input :id="column.prop" v-if="isFathEdit === column.prop && disabled === false" v-model="scope.row[column.prop]" @blur="isFathEdit=''"/>
            <span v-else >{{scope.row[column.prop]}}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="addVisible = false">取消</el-button>
      <el-button
        type="primary"
        @click="submit()"
        >确定</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue';
import { Plus, Minus } from '@element-plus/icons-vue'
import { useStaffStore } from '@/stores/staff';
import { dayjs } from 'element-plus';
import { saveDict, updateDict } from '@/api/dict'
import { getByDictType } from '@/api/public'
import { getDictsByType } from '@/api/dict'

  // 接收父组件方法
  const emit = defineEmits(['handle-change', 'get-dict-types'])
  // 接收父组件属性
  const props = defineProps({		// 通过defineProps "编译器宏"接收子组件传递的数据
    activeNames: Array
  })

  const modalName = ref('')
  const tableHeader = reactive([
      {
          'prop': 'seq',
      },
      {
          'prop': 'dictId',
          'label': '代码'
      },
      {
          'prop': 'dictName',
          'label': '码值'
      },
      {
          'prop': 'sortNo',
          'label': '排序号'
      },
      {
          'prop': 'isUsed',
          'label': '是否正在使用'
      }
  ])

  const fathTableHeader = reactive([
      {
        'prop': 'dictType',
        'label': '码表类型'
      },
      {
        'prop': 'dictTypeName',
        'label': '码表类型值'
      }
  ])

    let tableData = reactive([reactive(
      {   
        seq: 1,
        dictId: '',
        dictName: '',
        sortNo: '',
        isUsed: '1'
      })
    ])

    let fathTableData = reactive([reactive(
      {
        dictType: '',
        dictTypeName: ''
      })
    ])

    let dict = reactive({
      isUsed: [{
        dictId: '',
        dictName: ''
      }]
    })

    // 默认显示3行
    defaultRows()
    function defaultRows() {
      for(var count=2; count<=3; count++) {
        const row = reactive(
          {   
            seq: count,
            dictId: '',
            dictName: '',
            sortNo: '',
            isUsed: '1'
          })
          tableData.push(row)
      }
    }

  getDict('isUsed')
  async function getDict(dictTypes: string) {
    // 获取码表值
    await getByDictType({dictTypes: dictTypes}).then((res: any) => {
      if(res?.flag === true){
        // 需使用Object.assign给对象赋值，不然渲染有问题
        Object.assign(dict, res.data);
      }else{
        ElNotification.error(res.message)
      }
    }).catch((err: any) => {
      ElNotification.error(err)
    })
  }

  const disabled = ref(false)
  const addVisible = ref(false)
  const addParams = ref('添加参数')
  const modifyParams = ref('编辑参数')
  const showModal = async (row: any) => {
    if (row) {
      modalName.value = modifyParams.value
      disabled.value = true
      fathTableData = [{
        dictType: row.dictType,
        dictTypeName: row.dictTypeName
      }]
      await getDictByType(row.dictType)
      addVisible.value = true
    } else {
    tableData = reactive([reactive(
      {   
        seq: 1,
        dictId: '',
        dictName: '',
        sortNo: '',
        isUsed: '1'
      })
    ])

    fathTableData = reactive([reactive(
      {
        dictType: '',
        dictTypeName: ''
      })
    ])
      defaultRows()
      modalName.value = addParams.value
      disabled.value = false
      addVisible.value = true
    }
  }

  async function getDictByType(dictType: string) {
    getDictsByType({ dictType: dictType }).then((res: any) => {
        if(res?.flag === true){
          tableData = reactive([reactive(
            {   
              seq: 1,
              dictId: '',
              dictName: '',
              sortNo: '',
              isUsed: '1'
            })
          ])
          Object.assign(tableData, res.data)
          tableData.forEach((row, index) => {
            row.seq = index + 1
          })
        }else{
            ElNotification.error(res.message)
        }
      }).catch((err: any) => {
        ElNotification.error(err)
      })
  }

  const modalClose = () => {
    addVisible.value = false
  }

  defineExpose({
    showModal,
  })

  const insertRowNumber = ref<number>(1)
  const deleteRowNumber = ref<number>(1)
  const increase = (val: any) =>{
    if(val === 1){
      insertRowNumber.value ++
    }else if(val === 2){
      deleteRowNumber.value ++
    }
  }

  const decrease = (val: any) =>{
    if(val === 1 && insertRowNumber.value > 1){
      insertRowNumber.value --
    }else if(val === 2 && deleteRowNumber.value > 1){
      deleteRowNumber.value --
    }
  }

  const addTableData = () => {
  let seq = 0;
  if (tableData.length !== 0) {
    seq = tableData[tableData.length - 1].seq;
  }
  let tempArray = [];
  for (let count = seq + 1; count <= seq + insertRowNumber.value; count++) {
    let row = {
      seq: count,
      dictId: '',
      dictName: '',
      sortNo: '',
      isUsed: '1'
    };
    tempArray.push(row);
  }
  // 使用 push 将临时数组中的元素合并到 tableData
  tableData.push(...tempArray);
}


  // 删除行
  const deleteTableData = () =>{
      if(tableData.length < 1 || tableData.length < deleteRowNumber.value){
        ElNotification.error('无法删除')
        return
      }
      for(var count=1; count<=deleteRowNumber.value; count++) {
        tableData.pop()
    }
  }

  const isEdit = ref('')
  const rowIndex = ref()
  const handleCellDBClick = (row: any, column: any, cell: HTMLTableCellElement, event: Event) =>  {
    const columnName = column.property
    isEdit.value = columnName
    rowIndex.value = row.seq
    nextTick(() => {
      //input标签获取焦点
      let myElement = document.getElementById(columnName);
      if (myElement !== null) {
        myElement.focus()
      } else {
        // 处理 myElement 为 null 的情况
      }
    })
  }

  const isFathEdit = ref('')
  const handleFathCellDBClick = (row: any, column: any, cell: HTMLTableCellElement, event: Event) =>  {
    const columnName = column.property
    isFathEdit.value = columnName
    // fathRowIndex.value = row.seq
    nextTick(() => {
      //input标签获取焦点
      let myElement = document.getElementById(columnName);
      if (myElement !== null) {
        myElement.focus()
      } else {
        // 处理 myElement 为 null 的情况
      }
    })
  }

  const submit = () => {
    try{
      const dictType = fathTableData[0].dictType
      const dictTypeName = fathTableData[0].dictTypeName
      const userStore = useStaffStore()
      let submitData = [{
          dictType: '',
          dictTypeName: '',
          dictId: '',
          dictName: '',
          sortNo: '',
          isUsed: '1',
          createBy: '',
          createTime: ''
      }]
      Object.assign(submitData, tableData)
      submitData.forEach((dict: any) => {
        dict.dictType = dictType
        dict.dictTypeName = dictTypeName
        dict.createBy = userStore.staff.username
        dict.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

        // 判断字典是否存在空项
        if(Object.values(dict).some(value => value === null || value === undefined || value === '') === true){
          throw('请确认必填项是否均已填写')
        };
      })
      
      if(modalName.value === addParams.value){
        saveDict(submitData).then((res: any) => {
        if(res?.flag === true){
          addVisible.value = false
          ElNotification.success("添加成功")
          // 调用父组件方法
          getDictTypes()
        }else{
          ElNotification.error(res.data.message)
        }
        }).catch((err: any) => {
          ElNotification.error(err)
        })
      }else if(modalName.value === modifyParams.value){
        updateDict(submitData).then((res: any) => {
          if(res?.flag === true){
              addVisible.value = false
              ElNotification.success("修改成功")
              // 调用父组件方法
              handleChange(props.activeNames)
            }else{
              ElNotification.error(res.data.message)
            }
          }).catch((err: any) => {
            ElNotification.error(err)
          })
        }
      } catch (e) {
        ElNotification.error(e); // catch内容：终止循环
      }
  }

  const handleChange = ( dictType: any) => {     
    emit('handle-change', dictType)	// emit触发自定义事件并传递参数
  }

  const getDictTypes = () => {
    emit('get-dict-types')
  }

</script>
<style lang="scss" scoped>
.modify-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.insert-row {
  display: flex;
  align-items: center;
  margin-right: 30px;
}

.delete-row {
  display: flex;
  align-items: center;
}

.modify-row-btn {
  margin-left: 5px;
}

.minus-icon {
  margin-right: 10px;
}
.minus-icon:hover {
  color: var(--el-color-primary);
}

.plus-icon {
  margin-left: 10px;
}
.plus-icon:hover {
  color: var(--el-color-primary);
}

.cell-flex {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
